<template>
  <div class="normal-users">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>普通用户管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名/邮箱/手机号"
              style="width: 200px"
              class="mr-3"
              clearable
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleAdd">添加用户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
        <el-table-column prop="userId" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="120">
          <template #default="scope">
            {{ scope.row.nickname || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.sex || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.registerTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-popconfirm
                title="确定要删除该用户吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="handleDelete(scope.row)"
              >
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form 
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="userForm.address" type="textarea" :rows="2" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
          <div class="form-tip">不填写则使用默认密码：123456</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNormalUsers } from '@/api/admin'
import { addUser, updateUser, deleteUser } from '@/api/user'

// 状态变量
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const users = ref([])
const dialogVisible = ref(false)
const userForm = ref({})
const userFormRef = ref(null)
const dialogType = ref('add')

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 过滤用户列表
const filteredUsers = computed(() => {
  if (!searchQuery.value) return users.value
  
  const query = searchQuery.value.toLowerCase()
  return users.value.filter(user => 
    user.username?.toLowerCase().includes(query) ||
    user.nickname?.toLowerCase().includes(query) ||
    user.email?.toLowerCase().includes(query) ||
    user.phone?.includes(query)
  )
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const response = await getNormalUsers({
      page: currentPage.value,
      size: pageSize.value
    })
    
    if (response.code === 200 && response.data) {
      // 确保数据格式正确
      users.value = response.data.list.map(user => ({
        ...user,
        nickname: user.nickname || undefined,  // 确保 nickname 字段存在
        sex: user.sex || undefined,
        registerTime: user.registerTime || undefined
      }))
      total.value = response.data.total
      
      // 检查处理后的数据
      console.log('Processed users:', users.value)
    } else {
      console.error('Invalid response format:', response)
      ElMessage.error('获取用户列表失败')
    }
  } catch (error) {
    console.error('Error fetching users:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  userForm.value = {
    userId: row.userId,
    username: row.username,
    nickname: row.nickname || '',
    phone: row.phone || '',
    email: row.email || '',
    sex: row.sex || '男',
    address: row.address || '',
    role: row.role || '普通用户'
  }
  console.log('Editing user:', userForm.value)
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作将永久删除该用户的所有数据，不可恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteUser(row.userId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchUsers() // 刷新列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 处理表单提交
const handleSubmit = () => {
  userFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = dialogType.value === 'edit' ? {
          userId: userForm.value.userId,
          nickname: userForm.value.nickname,
          phone: userForm.value.phone,
          email: userForm.value.email,
          sex: userForm.value.sex || '男',
          address: userForm.value.address,
          role: userForm.value.role || '普通用户'
        } : {
          username: userForm.value.username,
          nickname: userForm.value.nickname || userForm.value.username,
          password: userForm.value.password || '123456',
          phone: userForm.value.phone,
          email: userForm.value.email,
          sex: userForm.value.sex || '男',
          address: userForm.value.address || '',
          role: '普通用户'
        };

        if (dialogType.value === 'add') {
          if (!submitData.username?.trim()) {
            ElMessage.error('用户名不能为空');
            return;
          }
          if (!submitData.phone?.trim()) {
            ElMessage.error('手机号不能为空');
            return;
          }
        }

        console.log('Submitting user data:', submitData);
        const api = dialogType.value === 'edit' ? updateUser : addUser;
        const response = await api(submitData);
        
        console.log('Server response:', response);
        
        if (response.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
          if (dialogType.value === 'add' && !userForm.value.password) {
            ElMessage.info('默认密码为: 123456');
          }
          dialogVisible.value = false;
          fetchUsers();
        } else {
          ElMessage.error(response.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
        }
      } catch (error) {
        console.error(`${dialogType.value === 'add' ? '添加' : '更新'}用户失败:`, error);
        const errorMsg = error.response?.data?.message || 
          (dialogType.value === 'add' ? '添加失败，请重试' : '更新失败，请重试');
        ElMessage.error(errorMsg);
      }
    }
  });
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 处理添加
const handleAdd = () => {
  dialogType.value = 'add'
  userForm.value = {
    username: '',
    nickname: '',
    phone: '',
    email: '',
    sex: '男',
    address: '',
    password: '',
    role: '普通用户'
  }
  dialogVisible.value = true
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.normal-users {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.mr-3 {
  margin-right: 12px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style> 